﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Guoc.BigMall.Infrastructure.Queue;
using Dapper;
using Dapper.DBContext;
using Guoc.BigMall.Infrastructure.Log;
using Guoc.BigMall.Infrastructure.IoC;
using Guoc.BigMall.Infrastructure.Caching;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Events;
using Guoc.BigMall.Web;
using Guoc.BigMall.Infrastructure.AutoMapper;
using Guoc.BigMall.Infrastructure.File;
using Guoc.BigMall.Domain;
using Guoc.BigMall.Infrastructure.Utils;
using Guoc.BigMall.WebService.Event;
using Guoc.BigMall.WebService.MapConfig;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure.Payment;
using Guoc.BigMall.Infrastructure.Payment.Wechat;
using Guoc.BigMall.Infrastructure.Payment.AliPay;
using Aop.Api;
using System.IO;

namespace Guoc.BigMall.Web.Services
{
    public class BootStrap
    {
        public static void InitAutofacContainer()
        {
            var builder = new ContainerBuilder();
            // Get your HttpConfiguration.
            // var config = GlobalConfiguration.Configuration;

            //  ASP.NET MVC Autofac RegisterDependency     
            Assembly webAssembly = Assembly.GetExecutingAssembly();
            builder.RegisterControllers(webAssembly);
            // OPTIONAL: Register the Autofac model binder provider.
            // builder.regist();

            // 注册系统组件代码
            // register admin service
            builder.RegisterType<AuthenticationService>().As<IAuthenticationService>().InstancePerLifetimeScope();
            //builder.RegisterType<ContextService>().As<IContextService>().InstancePerLifetimeScope();
            // register database connection            
            builder.RegisterType<DapperDBContext>().As<IDBContext>().WithParameter("connectionStringName", Configer.DBName);
            //  builder.RegisterType<QueryService>().As<IQuery>().WithParameter("connectionStringName", "masterDB");
            builder.RegisterType<NLogWriter>().As<ILogger>();

            //注册各层业务组件
            var typeFinder = new DefaultTypeFinder(new string[] { "Guoc.BigMall.WebService", "Guoc.BigMall.Domain" });
            var assemblies = typeFinder.LoadAssemblies();
            // builder.RegisterAssemblyTypes(assemblies).Where(t => t.Name.EndsWith("Service")).AsSelf();  // 领域服务
            builder.RegisterAssemblyTypes(assemblies).Where(t => t.Name.EndsWith("Facade")).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(assemblies).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();

            // 注册支付
            IDBContext db = new DapperDBContext(Configer.DBName);
           // var settings = db.Table<SystemSetup>().ToDictionary(n=>n.Name);
           // 注册配置信息
           var settings= db.Table<SystemSetup>().ToList().ToDictionary(k => k.Name, v => v.Value);
            builder.RegisterInstance(new SettingService(settings)).As<ISettings>().SingleInstance();

            // 注册微信支付
            var list = db.Table<WechatAccount>().ToList();
            var paylist = new PayService();
            foreach (var item in list)
            {
                paylist.AddGetway(new WechatGetway(new WechatConfig()
                {
                    AppId = item.AppId,
                    AppSecret = item.AppSecret,
                    MchId = item.MerchantId,
                    MchKey = item.MerchantKey,
                    NotifyUrl =string.Format("{0}{1}", settings[SettingKeys.System_Domain], settings[SettingKeys.Wechat_Pay_Notify]) ,
                    StoreCode = item.StoreCode,
                    SSlCertPath = settings[SettingKeys.Wechat_SSlCertPath]
                }));
            }
           // paylist.AddGetway(new AliPayGetway(new AliPayConfig()));
 
            builder.RegisterInstance(paylist).As<IPayService>().SingleInstance();

            // 注册支付宝支付
          var webRoot = AppDomain.CurrentDomain.BaseDirectory;
          webRoot = webRoot.Replace("\\", "/").TrimEnd('/');
          var certfiles= new CertParams
            {
                //请更换为您的应用公钥证书文件路径
                AlipayPublicCertPath = webRoot+settings[SettingKeys.Alipay_CertPublicKey],  // "/home/foo/alipayCertPublicKey_RSA2.crt",
                //请更换您的支付宝公钥证书文件路径
                AppCertPath = webRoot+settings[SettingKeys.Alipay_appcertpublickey],    // "/home/foo/appCertPublicKey_2019090366875133.crt",
                                                                                                    //请更换为支付宝根证书文件路径
              RootCertPath = webRoot+settings[SettingKeys.Alipay_rootcert]    //"/home/foo/alipayRootCert.crt"
          };

           var alipayclient=  new DefaultAopClient(
                    "https://openapi.alipay.com/gateway.do",
                    settings[SettingKeys.Alipay_Appid], //请更换为您的AppId
                    "MIIEpAIBAAKCAQEAjwCbXCr0prxOmHX+NJ61cBb971Lcaqls+gQ06IhuxH2BK6JSEu2JspTFrWuBJtVKoUQnVMMMMvoVAAwrrTcT0G8erA1gyqiNS+rrwuT6cI7Dytf0NPJ03aNhFWNcCwU4I4HMkyS/hESDWk1w5jc366S5TX+NIJTYkiy2QYIlmBfCDmFHmcnxMv50EjAkIa3O6T2lySYdOQ//Mtl7m/S6izLTMuWRplbOLUMhunV9G6GVNAmXpjkzKeTRt5lf0zP7DFrw4eaGV/sBuBCvkfL184A9rHVuqasAGY/OCq0pins2qpPWxGz4073BhHgv88Lsq4+oDvGxV/PE0qOCx1wLawIDAQABAoIBAGZfBNkiVynVvF4gee6pfzHTA86D/w7MYxtIT6f3o3Q+dG4MMb0jF2QkZK8VOsvV/SsdYxqm1uDXbpkuHUZPG3wnUEnS+euaZixm7IgE69QQH9HibwxIVaklAKcTDh1Fiz6/+PeNYx0I/w9ySNRFy16B+bWlDh6476EVKRQUW11Y7FCrmiCT/4om15MCLTTZB7EOT4OomzLZwhWTp8qswEnp2bTlObJQs+nNUK9XQHuytajBBmo0FNz8wcNMGqnJq4b5KJwf7tQoO7jtQ9irntPRTSvJAubO539E+Zb8Rc/AAaDfBn5CGKGxNPGUO1ytb+1ZrxAtbdsZjlG9vKck6SECgYEA7X87ziNHX3KOaZGSxtZpp8/8CR/Mxehg1oocTwjNu0d/FFHsT1AjGk4OAmMcVN5F94DXhEGh7Y7TxxdpkGTiLqNL4w3D1Y/zIq+F1SLu6/y8Kkftii+vFiNnTZjrIy0QqsR0Ul3EIyS6m+rflkFyrC5cp8BZ2NLDQCkRu5v9kO0CgYEAmiS42hCdENWNbnpzPRVzy+WxGOhWv/8uB5iT+wQ7K5Q6swi0CLI1U9Kg/vgkfc3lSd5JrKk4h35KbfTn8pUrHX3KPPdhxiusM6AkX/S/gdvJuS3M76F1Niq8LGRH7KzgKRvKT54/a4WepPwMQKP4ItV0rJJGDT/k+EeigXOa+rcCgYEAgVbYUBQAa6esjSudXrIoSh7HqIRr9Z/vFQeUESq/N+3g9EUFR9BhvZKiqIQnSsTeH8NIG5vOvtwY04UZlWyLjVCbJGU7sJO7mrkyTne+3EAAjZoscCQ12v2e5bCQ5dBGEmn42157UZRQGFeaOm8cL070YNstUxq9ALUdFioGtqUCgYBUHWPuQ5CiZha2ygVmuPUmuCILOIZWYXcJ2B4wpZ9waYQavM4ZzL3DDzahzGGFcT0FMVM88F8TuTv+gt2sB/CuOD2LRWfKj3x585LF9jYnM/wBnFewEIh41Zs4EkUZh0EPzcV56x4qm5D18UDyaUf4Ikl3/p5RjqNxRQ4N3DsfQwKBgQDcc/LGxpbB7dlODI6HTIp/AfAqqznDwm9zZharHlJPL/fezC3RXv0weh2Cb1xJtWa+6vUVts3sTkSnQ2iXPcLRoAbJKHdFjcSA6xOHwMexfxq7+ON2C+xW0MQX8sPm0uvwhTj5s9sBZBXAk4ZjNMGzHuvJsxVCE/JJ4ZmQu4L9HQ==", //请更换为您的PKCS1格式的应用私钥
                    "json", "1.0", "RSA2",
                    "utf-8", //请更换为您使用的字符集编码，推荐采用utf-8
                    false, certfiles);
            builder.RegisterInstance(alipayclient).As<IAopClient>().SingleInstance();

            //注册销售单队列处理，单例
            // builder.RegisterType<PosSyncFacade>().As<IQueueHander<string>>();
            builder.RegisterType<SimpleQueue<string>>().As<ISimpleQueue<string>>().SingleInstance();

            // 事件发布者和消费者
            builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance();
            builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance();
            // 消费者
            builder.RegisterType<SaleOrderPaidEventHandler>().As<IConsumer<SaleOrderPaidEvent>>().InstancePerLifetimeScope();

            // 注册缓存
            builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().SingleInstance();

            // 雪花算法
            builder.RegisterType<SnowflakeSequence>().As<ISequence>().WithParameter("workerId", 1L).SingleInstance();

            //数据导出
            builder.RegisterType<ExcelService>().As<IExcel>();
            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            // config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            // 初始化应用程序上下文
            Singleton<IContainerManager>.Instance = new AutofacContainer(container);

            //初始化AutoMapper
            // AutoMapperConfig.RegisterAll();
            AutoMapConfig.RegisterAll();

            //  注册支付配置信息

           // ILogger log = new NLogWriter();
           // log.Info("AppDomain.CurrentDomain.BaseDirectory={0}", AppDomain.CurrentDomain.BaseDirectory);
        }


    }
}